package com.czkt.conflg;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czkt.controller.DetailsController;
import com.czkt.pojo.Role;
import com.czkt.pojo.Vo.UserRoleMenuVo;
import com.czkt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * shixian
 */
@Component
public class CustoUserDeatailService implements UserDetailsService {
    @Autowired
    UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<com.czkt.pojo.User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(username != null, com.czkt.pojo.User::getUserName, username);
        com.czkt.pojo.User userList = userService.getOne(queryWrapper);
        if (userList==null){
            return null;
        }else {
            UserRoleMenuVo userRoleMenuVo =userService.userRoleMenu(username);
            List<GrantedAuthority> list = AuthorityUtils.createAuthorityList("ROLE_"+userRoleMenuVo.getRole().getRoleName());
            return new User(userList.getUserName(), new BCryptPasswordEncoder().encode(userList.getUserPassword()), list);
        }
    }
}
